# -*- coding: utf-8 -*-

# This code shows an example of text translation from English to Simplified-Chinese.
# This code runs on Python 2.7.x and Python 3.x.
# You may install `requests` to run this code: pip install requests
# Please refer to `https://api.fanyi.baidu.com/doc/21` for complete api document

import requests
import random
import json
from hashlib import md5


# query = 'Hello World! This is 1st paragraph.\nThis is 2nd paragraph.'
# query = 'technology, tech'

# Generate salt and sign
def make_md5(s, encoding='utf-8'):
    return md5(s.encode(encoding)).hexdigest()

def convert_to_chinese(query):
    # Set your own appid/appkey.
    appid = '20231106001871615'
    appkey = 'vgO81J_nTYfC6p1jLtC8'

    # For list of language codes, please refer to `https://api.fanyi.baidu.com/doc/21`
    from_lang = 'en'
    to_lang = 'zh'

    endpoint = 'http://api.fanyi.baidu.com'
    path = '/api/trans/vip/translate'
    url = endpoint + path
    salt = random.randint(32768, 65536)

    sign = make_md5(appid + query + str(salt) + appkey)

    # Build request
    headers = {'Content-Type': 'application/x-www-form-urlencoded'}
    payload = {'appid': appid, 'q': query, 'from': from_lang, 'to': to_lang, 'salt': salt, 'sign': sign}

    # Send request
    r = requests.post(url, params=payload, headers=headers)
    result = r.json()
    #result_dict = json.dumps(result, indent=4, ensure_ascii=False)
    # Output:
    print('result', result)
    if result and result['trans_result']:
        chinese_str = result.get('trans_result')[0].get('dst')
        print('chinese_str', chinese_str)
    else:
        chinese_str = ""
    return chinese_str

def convert_to_English(query):
    # Set your own appid/appkey.
    appid = '20231106001871615'
    appkey = 'vgO81J_nTYfC6p1jLtC8'

    # For list of language codes, please refer to `https://api.fanyi.baidu.com/doc/21`
    from_lang = 'zh'
    to_lang = 'en'

    endpoint = 'http://api.fanyi.baidu.com'
    path = '/api/trans/vip/translate'
    url = endpoint + path
    salt = random.randint(32768, 65536)

    sign = make_md5(appid + query + str(salt) + appkey)

    # Build request
    headers = {'Content-Type': 'application/x-www-form-urlencoded'}
    payload = {'appid': appid, 'q': query, 'from': from_lang, 'to': to_lang, 'salt': salt, 'sign': sign}

    # Send request
    r = requests.post(url, params=payload, headers=headers)
    result = r.json()
    #result_dict = json.dumps(result, indent=4, ensure_ascii=False)
    # Output:
    print('result', result)
    if result and result['trans_result']:
        English_str = result.get('trans_result')[0].get('dst')
        print('English_str', English_str)
    else:
        English_str = ""
    return English_str

# query = 'creation'
# convert_to_chinese(query)


query = '科技'
convert_to_English(query)
